<template>
  <div id = 'OrderGantt' style="height: 100%">
    <el-menu
      :default-active="1"
      class="el-menu-demo"
      mode="horizontal"
      @select="handleSelect"
      default-active="2"
      background-color="#545c64"
      text-color="#fff"
      active-text-color="#ffd04b">
      <el-menu-item index="0" class="menu_item" @click="toHomePage" style="width: 100px">
        <i class="el-icon-s-home" style="font-size: 50px; margin-right: 25px"></i>
      </el-menu-item>
      <el-menu-item index="1" class="menu_item" @click="toOrderGantt">订单甘特图</el-menu-item>
      <el-menu-item index="2" class="menu_item" @click="toResourceGantt">资源甘特图</el-menu-item>
      <el-menu-item index="3" class="menu_item" @click="toResourceLoad">资源负载图</el-menu-item>
      <el-menu-item index="4" class="menu_item">
        <a href="http://localhost/#/index">新系统</a>
      </el-menu-item>

      <div align="right" style="padding-right: 60px; margin-top: 10px">
        <el-input
          placeholder="请输入搜索内容"
          style="width: 300px"
          :disabled=inputDisable
          v-model="searchInput">
          <el-button slot="append" icon="el-icon-search" @click="trick" :disabled=inputDisable></el-button>
        </el-input>
      </div>
    </el-menu>
    <el-row>
      <el-col :span="12" style="height: 100%">
        <div align="right" style="padding-right: 150px; padding-top: 30px; font-size: 60px; font-weight: bold">资源甘特图</div>
      </el-col>
      <el-col :span="12">
        <br>
        <el-row class="date">当前日期 : {{curDate}}</el-row>
        <el-row style="padding-top: 10px">
          <el-date-picker
            v-model="selectedDate"
            type="date"
            placeholder="选择查询日期"
            size="large"
            style="width: 200px"
            class="date_picker">
          </el-date-picker>
          <el-button type="primary" @click="search">查询</el-button>
          <el-select v-model="selectedMode" style="width: 150px; padding-left: 150px" placeholder="请选择" @change="onModeChange">
            <el-option
              v-for="item in modes"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-row>
      </el-col>
    </el-row>
    <br>
    <el-row
      style="height: 50px;font-size: 30px;font-weight: bold; line-height: 50px">
      <el-col :span="18" :offset="5" style="height: 50px; background-color: #f4f4f5; border-style: solid" align="center" class="ganttBlock">
        <el-col :span="2">
          <div @mouseover="inLeft" @mouseout="outLeft"  @click="pre">
            <i class="el-icon-caret-left"></i>
          </div>
        </el-col>
        <el-col :span="20">资源占用</el-col>
        <el-col :span="2"@click="">
          <div @mouseover="inRight" @mouseout="outRight"  @click="post">
            <i class="el-icon-caret-right"></i>
          </div>
        </el-col>
      </el-col>
    </el-row>
    <el-row
      style="height: 80px;font-size: 20px;font-weight: bold; line-height: 80px; margin-bottom: 20px">
      <el-col :span="18" :offset="5" style="height: 80px" align="left">
        <el-col :span="1"></el-col>
        <el-col :span="3" v-for="day in days" align="center" style="border-style: solid">
          {{day}}
        </el-col>
      </el-col>
    </el-row>
    <el-row v-for="resource in resources" style="height: 60px; margin-bottom: 10px">
      <el-col :span="2" style="height: 100%; line-height: 60px; border-style: solid" :offset="1" align="center" class="ganttBlock">
        {{resource.resourceName}}
      </el-col>
      <el-col :span="2" style="height: 100%">
        <div align="right">
          <el-progress
            type="circle"
            :percentage="20"
            color="#409EFF"
            :stroke-width="10"
            :width="55"
            style="display: inline-block"
            class="progress"></el-progress>
        </div>
      </el-col>
      <el-col :span="18" style="height: 100%; padding: 0" align="left" class="ganttBlock">
        <div v-for="product in resource.products" :style="{width: product.width, backgroundColor: product.color, opacity: product.opacity, marginLeft: product.preWidth, lineHeight: '60px', display: 'inline-block', textAlign: 'center'}" class="ganttBlock"
          @click="highlight(product.productName, product.opacity)">
          {{product.productName}}
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
    import {getStaffGanttByDate, getDeviceGanttByDate} from "../api"

    export default {
        name: "ResourceGantt",
        data() {
            return {
                searchInput: '',
                inputDisable: false,
                isHighLighted: true,
                curDate: '2018-10-30',
                selectedDate: '',
                selectedMode: '0',
                days: [
                    '10/30',
                    '10/31',
                    '11/01',
                    '11/02',
                    '11/03',
                    '11/04',
                    '11/05',
                    '11/06'
                ],
                modes: [{
                    value: '0',
                    label: '全部资源'
                }, {
                    value: '1',
                    label: '仅员工'
                }, {
                    value: '2',
                    label: '仅设备'
                }],
                staffs: [
                    {
                        resourceId: 'resourceId',
                        resourceName: '张三',
                        useRate: '20%',
                        products: [
                            {
                                productId: 'productId2',
                                productName: 'productName2',
                                width: '20%',
                                preWidth: '10%',
                                color: '#4169e1',
                                opacity: '1'
                            },
                            {
                                productId: 'productId3',
                                productName: 'productName3',
                                width: '20%',
                                preWidth: '10%',
                                color: '#7fff00',
                                opacity: '1'
                            }
                        ]
                    },
                    {
                        resourceId: 'resourceId',
                        resourceName: '李四',
                        useRate: '20%',
                        products: [
                            {
                                productId: 'productId1',
                                productName: 'productName1',
                                width: '20%',
                                preWidth: '5%',
                                color: '#dc143c',
                                opacity: '1'
                            },
                            {
                                productId: 'productId2',
                                productName: 'productName2',
                                width: '20%',
                                preWidth: '5%',
                                color: '#4169e1'
                                ,opacity: '1'
                            },
                            {
                                productId: 'productId3',
                                productName: 'productName3',
                                width: '20%',
                                preWidth: '5%',
                                color: '#7fff00',
                                opacity: '1'
                            }
                        ]
                    },
                    {
                        resourceId: 'resourceId',
                        resourceName: '王五',
                        useRate: '20%',
                        products: [
                            {
                                productId: 'productId1',
                                productName: 'productName1',
                                width: '20%',
                                preWidth: '0%',
                                color: '#dc143c',
                                opacity: '1'
                            },
                            {
                                productId: 'productId2',
                                productName: 'productName2',
                                width: '20%',
                                preWidth: '20%',
                                color: '#4169e1',
                                opacity: '1'
                            },
                            {
                                productId: 'productId3',
                                productName: 'productName3',
                                width: '20%',
                                preWidth: '15%',
                                color: '#7fff00',
                                opacity: '1'
                            }
                        ]
                    }
                ],
                raw_staff: Map,
                devices: [
                    {
                        resourceId: 'resourceId',
                        resourceName: 'line1',
                        useRate: '20%',
                        products: [
                            {
                                productId: 'productId2',
                                productName: 'productName2',
                                width: '20%',
                                preWidth: '10%',
                                color: '#4169e1',
                                opacity: '1'
                            },
                            {
                                productId: 'productId3',
                                productName: 'productName3',
                                width: '20%',
                                preWidth: '10%',
                                color: '#7fff00',
                                opacity: '1'
                            }
                        ]
                    },
                    {
                        resourceId: 'resourceId',
                        resourceName: 'line2',
                        useRate: '20%',
                        products: [
                            {
                                productId: 'productId1',
                                productName: 'productName1',
                                width: '20%',
                                preWidth: '5%',
                                color: '#dc143c',
                                opacity: '1'
                            },
                            {
                                productId: 'productId2',
                                productName: 'productName2',
                                width: '20%',
                                preWidth: '5%',
                                color: '#4169e1'
                                ,opacity: '1'
                            },
                            {
                                productId: 'productId3',
                                productName: 'productName3',
                                width: '20%',
                                preWidth: '5%',
                                color: '#7fff00',
                                opacity: '1'
                            }
                        ]
                    },
                    {
                        resourceId: 'resourceId',
                        resourceName: 'line3',
                        useRate: '20%',
                        products: [
                            {
                                productId: 'productId1',
                                productName: 'productName1',
                                width: '20%',
                                preWidth: '0%',
                                color: '#dc143c',
                                opacity: '1'
                            },
                            {
                                productId: 'productId2',
                                productName: 'productName2',
                                width: '20%',
                                preWidth: '20%',
                                color: '#4169e1',
                                opacity: '1'
                            },
                            {
                                productId: 'productId3',
                                productName: 'productName3',
                                width: '20%',
                                preWidth: '15%',
                                color: '#7fff00',
                                opacity: '1'
                            }
                        ]
                    }
                ],
                raw_devices: Map,
                data_get: 0,
                resources: [],
                colorTable: [
                  "#dc143c",
                  "#4169e1",
                  "#7fff00",
                  "#ff1493",
                  "#3cb371",
                  "#ff00ff",
                  "#006400",
                  "#ffa500",
                  "#7b69ee"
                ]
            };
        },
        methods: {
            trick() {
                this.$alert('恭喜你发现了一个彩蛋，这个按钮实际上没有任何作用！^_^', 'TRICK!!!', {
                    confirmButtonText: '我知道了'
                });
                this.searchInput = '';
                this.inputDisable = true;
            },
            toHomePage(){
                this.$router.push({path: '/'});
            },
            toOrderGantt(){
                this.$router.push({path: '/OrderGantt'});
            },
            toResourceGantt(){
                this.$router.push({path: '/ResourceGantt'});
            },
            toResourceLoad(){
                this.$router.push({path: '/ResourceLoad'});
            },
            //高亮显示或去除高亮
            highlight(productName, opacity){
                this.onModeChange();
                if (parseFloat(opacity) < 1){
                    let newResources = [];
                    for (let j = 0; j < this.resources.length; j ++){
                        let r = this.resources[j];
                        let newProducts = [];
                        let shown = false;
                        for (let i = 0; i < r.products.length; i ++){
                            let p = r.products[i];
                            if (p.productName === productName){
                                newProducts[i] = {
                                    productName: p.productName,
                                    width: p.width,
                                    preWidth: p.preWidth,
                                    color: p.color,
                                    opacity: '1'
                                };
                                shown = true;
                            }
                            else{
                                newProducts[i] = {
                                    productName: p.productName,
                                    width: p.width,
                                    preWidth: p.preWidth,
                                    color: p.color,
                                    opacity: '0.4'
                                }
                            }
                        }
                        if (shown){
                            newResources[newResources.length] = {
                                resourceName: r.resourceName,
                                useRate: r.useRate,
                                products: newProducts
                            };
                        }
                    }
                    this.resources = newResources;
                    this.isHighLighted = true;
                }
                else {
                    if (!this.isHighLighted){
                        let newResources = [];
                        for (let j = 0; j < this.resources.length; j ++){
                            let r = this.resources[j];
                            let newProducts = [];
                            let shown = false;
                            for (let i = 0; i < r.products.length; i ++){
                                let p = r.products[i];
                                if (p.productName === productName){
                                    newProducts[i] = {
                                        productName: p.productName,
                                        width: p.width,
                                        preWidth: p.preWidth,
                                        color: p.color,
                                        opacity: '1'
                                    };
                                    shown = true;
                                }
                                else{
                                    newProducts[i] = {
                                        productName: p.productName,
                                        width: p.width,
                                        preWidth: p.preWidth,
                                        color: p.color,
                                        opacity: '0.4'
                                    }
                                }
                            }
                            if (shown){
                                newResources[newResources.length] = {
                                    resourceName: r.resourceName,
                                    useRate: r.useRate,
                                    products: newProducts
                                };
                            }
                        }
                        this.resources = newResources;
                        this.isHighLighted = true;
                    }
                    else {
                        this.isHighLighted = false;
                    }
                }


            },

            inLeft(){
                document.getElementsByClassName("el-icon-caret-left")[0].style.color = "yellow";
            },

            outLeft(){
                document.getElementsByClassName("el-icon-caret-left")[0].style.color = "black";
            },

            inRight(){
                document.getElementsByClassName("el-icon-caret-right")[0].style.color = "yellow";
            },

            outRight(){
                document.getElementsByClassName("el-icon-caret-right")[0].style.color = "black";
            },

            pre(){
              this.selectedDate.setDate(this.selectedDate.getDate() - 1);
              this.refreshCurDate();
            },

            post(){
              this.selectedDate.setDate(this.selectedDate.getDate() + 1);
              this.refreshCurDate();
            },

            /**
             * 显示模式改变
             */
            onModeChange() {
              this.reshowGantt();
            },

            /**
             * 重新展示甘特图
             */
            reshowGantt() {
              this.resources = [];
              if (this.selectedMode == '2') {
                this.fillDevicesIntoResources();
              } else {
                this.fillStaffsIntoResources();
                if (this.selectedMode == "0") {
                  this.fillDevicesIntoResources();
                }
              }
            },

            /**
             * 显示员工
             */
            fillStaffsIntoResources() {
              this.staffs.forEach(staff => {
                this.resources.push(staff);
              })
            },

            /**
             * 显示设备
             */
            fillDevicesIntoResources() {
              this.devices.forEach(device => {
                this.resources.push(device);
              })
            },

            /**
             * 选择日期并查询
             */
            search() {
              this.refreshCurDate();
            },

            /**
             * 更新当天日期
             */
            refreshCurDate() {
              this.curDate = this.dateFormat('YYYY-mm-dd', this.selectedDate);
              this.refreshDays();
              this.reshowGantt();
            },

            /**
             * 更新日期列表
             */
            refreshDays() {
              this.days = [];
              this.staffs = [];
              this.devices = [];
              var date = new Date(this.selectedDate.getTime());
              var date_str = this.dateFormat("YYYY-mm-dd", date);
              this.staffMap = new Map();
              this.deviceMap = new Map();
              this.data_get = 0;

              for (let index = 0; index < 8; index++) {
                this.days[index] = this.dateFormat("mm/dd", date);
                getStaffGanttByDate(date_str).then(res => {
                  res.forEach(staff => {
                    if (this.staffMap.get(staff.resourceName) == undefined) {
                      this.staffMap.set(staff.resourceName, staff.agenda);
                    } else {
                      staff.agenda.forEach(a => {
                        this.staffMap.get(staff.resourceName).push(a);
                      })
                    }
                  });
                  this.data_get = this.data_get + 1;
                })

                getDeviceGanttByDate(date_str).then(res => {
                  res.forEach(device => {
                    if (this.deviceMap.get(device.resourceName) == undefined) {
                      this.deviceMap.set(device.resourceName, device.agenda);
                    } else {
                      device.agenda.forEach(a => {
                        this.deviceMap.get(device.resourceName).push(a);
                      })
                    }
                  });
                  this.data_get = this.data_get + 1;
                })

                date.setDate(date.getDate() + 1);
                date_str = this.dateFormat('YYYY-mm-dd', date);
              }

              setTimeout(this.processRawData(), 100);
            },

            /**
             * 处理获取的原始数据
             */
            processRawData() {
              if (this.data_get < 16) {
                setTimeout(this.processRawData(), 100);
              } else {
                this.staffMap.forEach(function(products, resourceName, map) {
                  var staff_info = {
                    resourceId: resourceName,
                    resourceName: resourceName,
                    useRate: '20%',
                    products: []
                  }
                  var pre_product = undefined;
                  var pre_product_end = 0;
                  for (let i = 0; i <= products.length; i++) {
                    if (i == products.length) {
                      var block_width = (pre_product.endTime.getTime() - pre_product.startTime.getTime()) / (8 * 24 * 60 * 60 * 9.7);
                      var pre_width = (pre_product.startTime.getTime() - this.selectedDate.getTime()) / (8 * 24 * 60 * 60 * 9.7);
                      staff_info.products.push({
                        productId: pre_product.productId,
                        productName: pre_product.productName,
                        width: block_width + '%',
                        preWidth: pre_width + "%",
                        color: '#005eb8',
                        opacity: '0.4'})
                      break;
                    }
                    if (products[i].startTime > pre_product.endTime || (products[i].startTime == pre_product.endTime && products[i].productId != pre_product.productId)) {
                      var block_width = (pre_product.endTime.getTime() - pre_product.startTime.getTime()) / (8 * 24 * 60 * 60 * 9.7);
                      var pre_width = (pre_product.startTime.getTime() - this.selectedDate.getTime()) / (8 * 24 * 60 * 60 * 9.7);
                      staff_info.products.push({
                        productId: pre_product.productId,
                        productName: pre_product.productName,
                        width: block_width + '%',
                        preWidth: pre_width + "%",
                        color: '#005eb8',
                        opacity: '0.4'})
                        pre_product = products[i];
                        pre_product_end = pre_product_end + pre_width + block_width;
                    } else {
                      pre_product.endTime == products[i].endTime;
                    }
                  }
                  this.staffs.push(staff_info);
                });

                this.deviceMap.forEach(function(products, resourceId, map) {
                  var device_info = {
                    resourceId: resourceId,
                    resourceName: resourceId,
                    useRate: '20%',
                    products: []
                  }
                  var pre_content = undefined;
                  var pre_content_end = 0;
                  for (let i = 0; i <= content.length; i++) {
                    if (i == content.length) {
                      var block_width = (pre_content.endTime.getTime() - pre_content.startTime.getTime()) / (8 * 24 * 60 * 60 * 9.7);
                      var pre_width = (pre_content.startTime.getTime() - this.selectedDate.getTime()) / (8 * 24 * 60 * 60 * 9.7);
                      device_info.push({
                        productId: pre_content.productId,
                        productName: pre_content.productName,
                        width: block_width + '%',
                        preWidth: pre_width + "%",
                        color: '#005eb8',
                        opacity: '0.4'})
                      break;
                    }
                    if (products[i].startTime > pre_content.endTime || (products[i].startTime == pre_content.endTime && products[i].productId != pre_content.productId)) {
                      var block_width = (pre_content.endTime.getTime() - pre_content.startTime.getTime()) / (8 * 24 * 60 * 60 * 9.7);
                      var pre_width = (pre_content.startTime.getTime() - this.selectedDate.getTime()) / (8 * 24 * 60 * 60 * 9.7);
                      device_info.push({
                        productId: pre_content.productId,
                        productName: pre_content.productName,
                        width: block_width + '%',
                        preWidth: pre_width + "%",
                        color: '#005eb8',
                        opacity: '0.4'})
                        pre_content = products[i];
                        pre_content_end = pre_content_end + pre_width + block_width;
                    } else {
                      pre_content.endTime == products[i].endTime;
                    }
                  }
                  this.devices.push(device_info);
                })
              }
              this.reshowGantt();
            },

            /**
             * 获取下一天
             * @param {string} day 源日期，日期格式 YYYY-mm-dd
             * @returns {Date} 源日期的下一天
             */
            getNextDay(day) {
              var day_data = day.split('-');
              var src_day = new Date(0);
              src_day.setFullYear(parseInt(day_data[0]));
              src_day.setMonth(parseInt(day_data[1] - 1));
              src_day.setDate(parseInt(day_data[2]));
              return new Date(src_day.getTime() + 24 * 60 * 60 * 1000);
            },

            /**
             * 格式化Date对象为
             * YYYY-mm-dd HH:MM:SS
             * @param {Date} date 目标日期
             */
            dateFormat(fmt, date) {
              let ret;
              const opt = {
                "Y+": date.getFullYear().toString(),        // 年
                "m+": (date.getMonth() + 1).toString(),     // 月
                "d+": date.getDate().toString(),            // 日
                "H+": date.getHours().toString(),           // 时
                "M+": date.getMinutes().toString(),         // 分
                "S+": date.getSeconds().toString()          // 秒
                // 有其他格式化字符需求可以继续添加，必须转化成字符串
              };
              for (let k in opt) {
                ret = new RegExp("(" + k + ")").exec(fmt);
                if (ret) {
                  fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
                };
              };
              return fmt;
            }
        },
        mounted: function () {
          this.reshowGantt()
        }
    }
</script>

<style scoped>

  .menu_item {
    width: 150px;
    font-size: larger;
    text-align: center;
    font-weight: bold;
  }

  .title {
    text-align: center;
    font-size: 60px;
    font-weight: bold;
    margin-top: 20px;
    margin-bottom: 10px;
  }

  .progress {
    font-weight: bold;
    font-size: 20px;
    margin-left: auto;
    margin-right: 40px;
  }

  .date {
    font-size: 40px;

  }

  .date_picker {
    height: 60px;
    line-height: 60px;
    width: 300px;
  }
</style>
